package com.fengye.middleware.rabbitmq.boot.ack.manual;

import lombok.extern.slf4j.Slf4j;
import org.springframework.amqp.core.*;
import org.springframework.amqp.rabbit.connection.CachingConnectionFactory;
import org.springframework.amqp.rabbit.listener.SimpleMessageListenerContainer;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Qualifier;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.boot.autoconfigure.amqp.SimpleRabbitListenerContainerFactoryConfigurer;
import org.springframework.context.annotation.Bean;
import org.springframework.stereotype.Component;

/**
 *
 * @author sky
 * @date 2021年06月09日 2:21 下午
 */
@Component
@Slf4j
public class KnowledgeManualConfig {

    @Value("${mq.knowledge.manual.queue.name:manual_queue_name}")
    private String manualQueueName;

    @Value("${mq.knowledge.manual.exchange.name:manual_change_name}")
    private String manualExchangeName;

    @Value("${mq.knowledge.manual.routing.key.name:manual_routing_key_name}")
    private String manualRoutingKeyName;

    @Autowired
    private KnowledgeManualConsumer knowledgeManualConsumer;

    /* 创建简单消息模型：队列、交换机和路由 */

    // 队列
    @Bean(name = "manualQueue")
    public Queue manualQueue() {
        return new Queue(manualQueueName);
    }

    @Bean(name = "manualExchange")
    public DirectExchange manualExchange() {
        return new DirectExchange(manualExchangeName, true, false);
    }

    @Bean
    public Binding manualBinding(Queue manualQueue, DirectExchange manualExchange) {
        return BindingBuilder.bind(manualQueue).to(manualExchange).with(manualRoutingKeyName);
    }

    @Autowired
    private CachingConnectionFactory cachingConnectionFactory;

    @Autowired
    private SimpleRabbitListenerContainerFactoryConfigurer factoryConfigurer;

    @Bean(name = "singleListenerContainerManual")
    public SimpleMessageListenerContainer listenerContainerManual(@Qualifier("manualQueue") Queue manualQueue) {
        SimpleMessageListenerContainer container = new SimpleMessageListenerContainer();
        container.setConnectionFactory(cachingConnectionFactory);
        // 设置消息在传输中的格式，在这里采用 JSON 格式进行传输
        // container.setMessageConverter(new Jackson2JsonMessageConverter());

        // 设置并发消费者示例的初始数量
        container.setConcurrentConsumers(1);

        // 设置并发消费者示例的最大数量
        container.setMaxConcurrentConsumers(1);

        // 设置并发消费者示例中每个示例拉取的数量
        container.setPrefetchCount(1);

        container.setAcknowledgeMode(AcknowledgeMode.MANUAL);

        container.setQueues(manualQueue);

        container.setMessageListener(knowledgeManualConsumer);

        return container;
    }
}
